package com.xz.sales.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.logging.Logger;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xz.apply.domain.PurchaseProductApply;
import com.xz.apply.mapper.PurchaseProductApplyMapper;
import com.xz.apply.service.IPurchaseApplyService;
import com.xz.common.core.domain.AjaxResult;
import com.xz.common.exception.ServiceException;
import com.xz.common.service.ISysAccessoryService;
import com.xz.common.utils.DateUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.common.utils.SecurityUtils;
import com.xz.common.utils.StringUtils;
import com.xz.diagnosis.vo.SalesPurchaseApplyVo;
import com.xz.diagnosisOrder.domain.DiagnosisTreatmentOrder;
import com.xz.message.service.ISysTenantNotifyItemService;
import com.xz.message.vo.MemberMsgInfo;
import com.xz.purchaseOrder.domain.PurchaseProductOrder;
import com.xz.sales.domain.SalesOrder;
import com.xz.sales.mapper.SalesOrderMapper;
import com.xz.sales.param.SalesDetailParam;
import com.xz.sales.util.ProcessOrderUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xz.sales.mapper.SalesOrderDetailMapper;
import com.xz.sales.domain.SalesOrderDetail;
import com.xz.sales.service.ISalesOrderDetailService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 销售单商品明细Service业务层处理
 *
 * @author xz
 * @date 2024-01-31
 */
@Service
public class SalesOrderDetailServiceImpl  extends ServiceImpl<SalesOrderDetailMapper, SalesOrderDetail> implements ISalesOrderDetailService
{
    @Autowired
    private SalesOrderDetailMapper salesOrderDetailMapper;
    @Resource
    private SalesOrderMapper salesOrderMapper;
    @Autowired
    private ISysAccessoryService iSysAccessoryService;
    @Resource
    private PurchaseProductApplyMapper purchaseProductApplyMapper;
    @Autowired
    private IPurchaseApplyService purchaseApplyService;
    @Autowired
    private ISysTenantNotifyItemService sysTenantNotifyItemService;

    /**
     * 查询销售单商品明细
     *
     * @param id 销售单商品明细主键
     * @return 销售单商品明细
     */
    @Override
    public SalesOrderDetail selectSalesOrderDetailById(Long id)
    {
        return salesOrderDetailMapper.selectSalesOrderDetailById(id);
    }

    /**
     * 查询销售单商品明细列表
     *
     * @param salesOrderDetail 销售单商品明细
     * @return 销售单商品明细
     */
    @Override
    public List<SalesOrderDetail> selectSalesOrderDetailList(SalesOrderDetail salesOrderDetail)
    {
        return salesOrderDetailMapper.selectSalesOrderDetailList(salesOrderDetail);
    }

    @Override
    public List<SalesOrderDetail> chooseDetailList(SalesDetailParam salesDetailParam){
        return salesOrderDetailMapper.chooseDetailList(salesDetailParam);
    }

    /**
     * 新增销售单商品明细
     *
     * @param salesOrderDetail 销售单商品明细
     * @return 结果
     */
    @Override
    public int insertSalesOrderDetail(SalesOrderDetail salesOrderDetail)
    {
        salesOrderDetail.setCreateTime(DateUtils.getNowDate());
        return salesOrderDetailMapper.insertSalesOrderDetail(salesOrderDetail);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateStatus(SalesOrderDetail salesOrderDetail){
        SalesOrderDetail orderDetail = baseMapper.selectById(salesOrderDetail.getId());
        if(Objects.nonNull(salesOrderDetail.getProductStatus())){
            // 说明更新状态
            orderDetail.setProductStatus(salesOrderDetail.getProductStatus());
            if(salesOrderDetail.getProductStatus().equals(11)){
                StringBuilder stringBuilder = new StringBuilder();
                String transferInfo = orderDetail.getTransferInfo();
                if(StringUtils.isNotEmpty(transferInfo)){
                    stringBuilder.append(transferInfo).append(";");
                }

                if(StringUtils.isNotEmpty(salesOrderDetail.getSigner())){
                    stringBuilder.append("签收人:").append(salesOrderDetail.getSigner()).append(";");
                }

                if(StringUtils.isNotEmpty(salesOrderDetail.getTrackingNumber())){
                    stringBuilder.append("快递单号:").append(salesOrderDetail.getTrackingNumber()).append(";");
                }
                // 发送账户变动短信
               /* MemberMsgInfo msgInfo = new MemberMsgInfo();

                sysTenantNotifyItemService.sendMemberInfoMsg(msgInfo,2, SecurityUtils.getLoginUser().getUser());
*/
                orderDetail.setTransferInfo(stringBuilder.toString());
            }
        }
        if(Objects.nonNull(salesOrderDetail.getTransferMethod())){
            StringBuilder stringBuilder = new StringBuilder();
            String transferInfo = salesOrderDetail.getTransferInfo();
            if(salesOrderDetail.getTransferMethod().equals(1)){
                stringBuilder.append("人工移交;");
            }else {
                stringBuilder.append("邮寄;");
            }
            orderDetail.setTransferMethod(salesOrderDetail.getTransferMethod());
            orderDetail.setTransferInfo(stringBuilder.append(transferInfo).toString());
        }
        if(StringUtils.isNotEmpty(salesOrderDetail.getFileUrl())){
            if(Objects.nonNull(salesOrderDetail.getUploadFileType()) && salesOrderDetail.getUploadFileType().equals(2)){
                // 看需不需要定制采购的附件
                PurchaseProductApply productApply = purchaseProductApplyMapper.selectSalesProduct(orderDetail.getSalesId(), orderDetail.getId());
                if(Objects.nonNull(productApply)){
                    productApply.setProductUrl(salesOrderDetail.getFileUrl());
                    productApply.setProductUrlName(salesOrderDetail.getFileName());
                    purchaseProductApplyMapper.updateById(productApply);
                }
            }

            orderDetail.setFileUrl(salesOrderDetail.getFileUrl());
            orderDetail.setFileName(salesOrderDetail.getFileName());
        }
        if(salesOrderDetail.getWarehouseId()!=null){
            orderDetail.setWarehouseId(salesOrderDetail.getWarehouseId());
            orderDetail.setWarehouseName(salesOrderDetail.getWarehouseName());
        }
        baseMapper.updateById(orderDetail);


        // 只有定制采购的才可以上传参数附件吧
        if(Objects.nonNull(salesOrderDetail.getUploadFileType()) && salesOrderDetail.getUploadFileType().equals(1)){
            List<SalesOrderDetail> detailList = baseMapper.selectBySalesId(orderDetail.getSalesId());
            List<SalesOrderDetail> collect = detailList.stream()
                    .filter(o -> o.getProductPurchaseType().equals(2) && o.getProductStatus().equals(3)).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(collect)){
                // 说明没有待上传参数的定制采购商品了 生成定制采购单了
                SalesOrder salesOrder = salesOrderMapper.selectSalesOrderById(orderDetail.getSalesId());
                SalesPurchaseApplyVo salesPurchaseApplyVo = new SalesPurchaseApplyVo();
                salesPurchaseApplyVo.setSalesNo(salesOrder.getSalesNo());
                salesPurchaseApplyVo.setSalesDeptId(salesOrder.getDeptId());
                salesPurchaseApplyVo.setSalesOrderId(salesOrder.getId());
                List<SalesOrderDetail> dzcgList = detailList.stream().filter(o -> o.getProductPurchaseType().equals(2)).collect(Collectors.toList());
                salesPurchaseApplyVo.setOrderDetailList(dzcgList);
                purchaseApplyService.addSalesPurchaseApply(salesPurchaseApplyVo);
            }
        }

//        if(StringUtils.isNotEmpty(salesOrderDetail.getUrlPath())){
//            //删除历史附件
//            iSysAccessoryService.deleteSysAccessoryByBizId(salesOrderDetail.getId().toString(),4);
//            List<String> urlList = new ArrayList<>();
//            urlList.add(salesOrderDetail.getUrlPath());
//            List<Object> resultList = JSON.parseArray(JSON.toJSONString(urlList), Object.class);
//            iSysAccessoryService.insertUrlList(resultList,salesOrderDetail.getId().toString(),4,2);
//        }
        // 遍历更新销售单状态
        List<SalesOrderDetail> salesOrderDetails = baseMapper.selectBySalesId(orderDetail.getSalesId());
        Integer orderStatus = ProcessOrderUtil.processOrderStatusByDetails(salesOrderDetails);
        salesOrderMapper.updateOrderStatus(orderDetail.getSalesId(),orderStatus);
        return AjaxResult.success("操作成功！");

    }

    @Override
    public Integer getNextStatus(Long orderDetailId,Integer bizType){
        SalesOrderDetail salesOrderDetail = baseMapper.selectById(orderDetailId);
        if(bizType.equals(1)){
            if(Objects.isNull(salesOrderDetail)){
                return -1;
            }
            if(salesOrderDetail.getMachiningType().equals(1)){
                return 8;
            }
        }
        // 如果不需要加工 则交付 交付的时候 判断销售单交付方式
       /*  SalesOrder salesOrder = salesOrderMapper.selectById(salesOrderDetail.getSalesId());
       if(salesOrder.getDeliveryMethod().equals(1)){
            return 10;
        }else {
            return 11;
        }*/
        return 11;
    }

    /**
     * 修改销售单商品明细
     *
     * @param salesOrderDetail 销售单商品明细
     * @return 结果
     */
    @Override
    public int updateSalesOrderDetail(SalesOrderDetail salesOrderDetail)
    {
        salesOrderDetail.setUpdateTime(DateUtils.getNowDate());
        return salesOrderDetailMapper.updateSalesOrderDetail(salesOrderDetail);
    }

    /**
     * 批量删除销售单商品明细
     *
     * @param ids 需要删除的销售单商品明细主键
     * @return 结果
     */
    @Override
    public int deleteSalesOrderDetailByIds(Long[] ids)
    {
        return salesOrderDetailMapper.deleteSalesOrderDetailByIds(ids);
    }

    /**
     * 删除销售单商品明细信息
     *
     * @param id 销售单商品明细主键
     * @return 结果
     */
    @Override
    public int deleteSalesOrderDetailById(Long id)
    {
        return salesOrderDetailMapper.deleteSalesOrderDetailById(id);
    }


}
